import os
import random
import shutil
import traceback
import warnings
import platform
import re

from xjlibrary.tools.BaseString import BaseString
from xjlibrary.tools.base_utils import deprecated


@deprecated
class BaseFile(BaseString):

    @classmethod
    def readline(cls, file_path, encoding="utf-8"):
        """
        按行读取文件
        :param file_path:
        :param encoding:
        :return:
        """
        try:
            with open(file_path, "r", encoding=encoding) as f:
                for line in f.readlines():
                    yield line.replace("\n", "")
        except:
            print(traceback.format_exc())

    @classmethod
    def get_path_absolute(cls, file):
        """
        请传入 __file__ 作为参数
        获取一个文件的绝对路径
        :param __file__:
        :return:
        """
        curPath = os.path.dirname(os.path.abspath(file))
        return curPath

    @classmethod
    def get_top_path(cls, curPath, num):
        """
        获取上几层的目录
        :param curPath:
        :param num:
        :return:
        """
        # 如果不是个整数
        if not isinstance(num, int) or num > 0:
            warnings.warn("this not int or num > 0 , The path is not processed, return curPath")
            return curPath
        pathlist = curPath.split(os.sep)
        if abs(num) > (len(pathlist) - 1):
            warnings.warn("this path length < num ,will return root dir ")
            num = (len(pathlist) - 1) * (-1)
        pathlist = pathlist[:num]
        TopPath = os.sep.join(pathlist)
        return TopPath

    @classmethod
    def getNewPath(cls, path, *paths):
        """
        通过当前目录组合新的目录
        :return:
        """
        if platform.system() == "Windows":
            if (re.match("^[A-Za-z]:$", path)):
                path = path + "\\"
        path = os.path.join(path, *paths)
        return path

    @classmethod
    def check_create_dir(cls, path):
        """
        检查和创建目录
        :param path:
        :return:
        """
        if os.path.exists(path):
            return True
        else:
            os.makedirs(path)
            return False


# 单次将内容写入文件
@deprecated
def SingleWriteFile(value, files, encoding="utf-8"):
    """
    写入值到文件 每次写入会覆盖原来的文件  文件不存在会自动创建
    :param value:
    :param files:
    :return:
    """
    with open(files, 'w', encoding=encoding) as f:
        f.write(value)


@deprecated
def SingleReadFile(filePath, encoding="utf-8"):
    """
    读取文件中的所有值
    :param filePath:
    :param encoding:
    :return:
    """
    with open(filePath, encoding=encoding) as f:
        return f.read()


@deprecated
def ReadFileRBYield(filePath):
    with open(filePath, "rb") as f:
        for fLine in f:
            yield fLine


@deprecated
def SingleAddFile(value, filePath, encoding="utf-8"):
    """
    追加文件中的所有值
    :param filePath:
    :param encoding:
    :return:
    """
    with open(file=filePath, mode="a", encoding=encoding) as f:
        f.write(value)


@deprecated
def AddFileAB(value, filePath):
    """
    追加文件中的所有值
    :param filePath:
    :param encoding:
    :return:
    """
    with open(file=filePath, mode="ab") as f:
        f.write(value)


@deprecated
def copyFile(fileDir, tarDir, num):
    # 获取目录下的所有文件名和目录
    pathDir = os.listdir(fileDir)

    # 随机获取
    sample = random.sample(pathDir, num)

    for name in sample:
        shutil.copyfile(os.path.join(fileDir, name), os.path.join(tarDir, name))

# if __name__ == "__main__":
#     for lien in BaseFile.readline("test.txt.txt"):
#         print(lien)
